using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Security.Permissions;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;

using EF;

namespace EF.Features.EFInspectUniquePerm
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("3c4eb687-d215-4832-8afd-07e817dc1b25")]
    public class EFInspectUniquePermEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public void logDebug(string strMessage)
        {
            EF.EFInspectUniquePerm.logTraceInfo(strMessage);
        }

        //public void logDebugHistory(SPWeb objSPWeb, string strMessage)
        //{
        //    EFInspectUniquePerm.logDebugHistory(objSPWeb, strMessage, this.GetType().Assembly);
        //}

        // Uncomment the method below to handle the event raised after a feature has been activated.
        public void initLists(SPSite site)
        {
            SPList splistResult = null;
            SPView oViewResult = null;
            SPViewFieldCollection oViewFieldsResult = null;
            Guid guidResult = Guid.Empty;

            SPList splistHistory = null;
            SPView oViewHistory = null;
            SPViewFieldCollection oViewFieldsHistory = null;
            Guid guidHistory = Guid.Empty;

            string strViewQuery = string.Empty;
            string strViewQueryTemplate = string.Empty;
            StringCollection viewFields = null;

            try
            {
                splistResult = site.RootWeb.Lists.TryGetList(EF.EFInspectUniquePerm.Result_ListTitle);
                if (splistResult != null)
                    splistResult.Delete();
                //if (splistResult == null)
                {
                    guidResult = site.RootWeb.Lists.Add(EF.EFInspectUniquePerm.Result_ListTitle, EF.EFInspectUniquePerm.Result_ListDescription, SPListTemplateType.GenericList);
                    splistResult = site.RootWeb.Lists[guidResult];

                    splistResult.Fields.Add(EF.EFInspectUniquePerm.Column_Result_ObjectType, SPFieldType.Choice, true);
                    SPFieldChoice objSPFieldObjectType = (SPFieldChoice)splistResult.Fields[EF.EFInspectUniquePerm.Column_Result_ObjectType];
                    objSPFieldObjectType.Choices.Add(EF.EFInspectUniquePerm.ObjectType.Web.ToString());
                    objSPFieldObjectType.Choices.Add(EF.EFInspectUniquePerm.ObjectType.List.ToString());
                    objSPFieldObjectType.Choices.Add(EF.EFInspectUniquePerm.ObjectType.Folder.ToString());
                    objSPFieldObjectType.Choices.Add(EF.EFInspectUniquePerm.ObjectType.Item.ToString());
                    objSPFieldObjectType.DefaultValue = EF.EFInspectUniquePerm.ObjectType.Web.ToString();
                    objSPFieldObjectType.Update();

                    splistResult.Fields.Add(EF.EFInspectUniquePerm.Column_Result_ModifiedByUser, SPFieldType.User, false);
                    splistResult.Fields.Add(EF.EFInspectUniquePerm.Column_Result_ModifiedTime, SPFieldType.DateTime, false);
                    SPFieldDateTime objSPFieldModifiedTime = (SPFieldDateTime)splistResult.Fields[EF.EFInspectUniquePerm.Column_Result_ModifiedTime];
                    objSPFieldModifiedTime.DisplayFormat = SPDateTimeFieldFormatType.DateTime;
                    objSPFieldModifiedTime.Update();

                    splistResult.Fields.Add(EF.EFInspectUniquePerm.Column_Result_WebUrl, SPFieldType.Text, false);
                    splistResult.Fields.Add(EF.EFInspectUniquePerm.Column_Result_ParentUrl, SPFieldType.Text, false);
                    splistResult.Fields.Add(EF.EFInspectUniquePerm.Column_Result_Link, SPFieldType.URL, true);

                    splistResult.Fields.Add(EF.EFInspectUniquePerm.Column_Result_UserRights, SPFieldType.Note, false);
                    SPFieldMultiLineText objSPFieldWebTitle = (SPFieldMultiLineText)splistResult.Fields[EF.EFInspectUniquePerm.Column_Result_UserRights];
                    objSPFieldWebTitle.RichText = false;
                    objSPFieldWebTitle.RichTextMode = SPRichTextMode.Compatible;
                    splistResult.Fields.Add(EF.EFInspectUniquePerm.Column_Result_ScanTime, SPFieldType.DateTime, false);
                    SPFieldDateTime objSPFieldLastScanTime = (SPFieldDateTime)splistResult.Fields[EF.EFInspectUniquePerm.Column_Result_ScanTime];
                    objSPFieldLastScanTime.DisplayFormat = SPDateTimeFieldFormatType.DateTime;
                    objSPFieldLastScanTime.Update();

                    objSPFieldWebTitle.Update();

                    splistResult.EnableAttachments = false;
                    splistResult.Update();

                    oViewResult = splistResult.DefaultView;
                    oViewFieldsResult = oViewResult.ViewFields;
                    oViewFieldsResult.Add(splistResult.Fields[EF.EFInspectUniquePerm.Column_Result_ObjectType]);
                    //oViewFieldsResult.Add(splistResult.Fields[SPBuiltInFieldId.Title]);
                    oViewFieldsResult.Add(splistResult.Fields[EF.EFInspectUniquePerm.Column_Result_ModifiedByUser]);
                    oViewFieldsResult.Add(splistResult.Fields[EF.EFInspectUniquePerm.Column_Result_ModifiedTime]);
                    oViewFieldsResult.Add(splistResult.Fields[EF.EFInspectUniquePerm.Column_Result_WebUrl]);
                    oViewFieldsResult.Add(splistResult.Fields[EF.EFInspectUniquePerm.Column_Result_ParentUrl]);
                    oViewFieldsResult.Add(splistResult.Fields[EF.EFInspectUniquePerm.Column_Result_Link]);
                    oViewFieldsResult.Add(splistResult.Fields[EF.EFInspectUniquePerm.Column_Result_UserRights]);
                    //oViewFieldsResult.Add(splistResult.Fields[EF.EFInspectUniquePerm.Column_Result_ScanTime]);

                    oViewResult.TabularView = false;
                    oViewResult.Update();

                    viewFields = new StringCollection();
                    viewFields.Add(EF.EFInspectUniquePerm.Column_Result_ObjectType);
                    //viewFields.Add(splistResult.Fields[SPBuiltInFieldId.Title].Title);
                    viewFields.Add(EF.EFInspectUniquePerm.Column_Result_ModifiedByUser);
                    viewFields.Add(EF.EFInspectUniquePerm.Column_Result_ModifiedTime);
                    viewFields.Add(EF.EFInspectUniquePerm.Column_Result_WebUrl);
                    viewFields.Add(EF.EFInspectUniquePerm.Column_Result_ParentUrl);
                    viewFields.Add(EF.EFInspectUniquePerm.Column_Result_Link);
                    viewFields.Add(EF.EFInspectUniquePerm.Column_Result_UserRights);
                    viewFields.Add(EF.EFInspectUniquePerm.Column_Result_ScanTime);

                    strViewQueryTemplate = @"<Eq><FieldRef Name='" + EF.EFInspectUniquePerm.Column_Result_ObjectType + @"' /><Value Type='Choice'>{0}</Value></Eq>";
                    strViewQueryTemplate = @"<Where>" + strViewQueryTemplate + @"</Where>";
                    strViewQuery = string.Format(strViewQueryTemplate, EF.EFInspectUniquePerm.ObjectType.Web);
                    splistResult.Views.Add(EF.EFInspectUniquePerm.View_Web, viewFields, strViewQuery, 300, true, false);
                    strViewQuery = string.Format(strViewQueryTemplate, EF.EFInspectUniquePerm.ObjectType.List);
                    splistResult.Views.Add(EF.EFInspectUniquePerm.View_List, viewFields, strViewQuery, 300, true, false);
                    strViewQuery = string.Format(strViewQueryTemplate, EF.EFInspectUniquePerm.ObjectType.Library);
                    splistResult.Views.Add(EF.EFInspectUniquePerm.View_Library, viewFields, strViewQuery, 300, true, false);
                    strViewQuery = string.Format(strViewQueryTemplate, EF.EFInspectUniquePerm.ObjectType.Folder);
                    splistResult.Views.Add(EF.EFInspectUniquePerm.View_Folder, viewFields, strViewQuery, 300, true, false);
                    strViewQuery = string.Format(strViewQueryTemplate, EF.EFInspectUniquePerm.ObjectType.Item);
                    splistResult.Views.Add(EF.EFInspectUniquePerm.View_Item, viewFields, strViewQuery, 300, true, false);
                    strViewQuery = string.Format(strViewQueryTemplate, EF.EFInspectUniquePerm.ObjectType.File);
                    splistResult.Views.Add(EF.EFInspectUniquePerm.View_File, viewFields, strViewQuery, 300, true, false);
                }

                //make sure the history list is already created
                splistHistory = site.RootWeb.Lists.TryGetList(EF.EFInspectUniquePerm.History_ListTitle);
                if (splistHistory != null)
                    splistHistory.Delete();

                guidHistory = site.RootWeb.Lists.Add(EF.EFInspectUniquePerm.History_ListTitle, EF.EFInspectUniquePerm.History_ListDescription, SPListTemplateType.GenericList);
                splistHistory = site.RootWeb.Lists[guidHistory];
                splistHistory.Fields.Add(EF.EFInspectUniquePerm.Column_History_WebCount, SPFieldType.Number, false);
                splistHistory.Fields.Add(EF.EFInspectUniquePerm.Column_History_ListCount, SPFieldType.Number, false);
                splistHistory.Fields.Add(EF.EFInspectUniquePerm.Column_History_LibraryCount, SPFieldType.Number, false);
                splistHistory.Fields.Add(EF.EFInspectUniquePerm.Column_History_FolderCount, SPFieldType.Number, false);
                splistHistory.Fields.Add(EF.EFInspectUniquePerm.Column_History_ItemCount, SPFieldType.Number, false);
                splistHistory.Fields.Add(EF.EFInspectUniquePerm.Column_History_FileCount, SPFieldType.Number, false);
                splistHistory.Fields.Add(EF.EFInspectUniquePerm.Column_History_ActionType, SPFieldType.Choice, false);
                SPFieldChoice objSPFieldActionType = (SPFieldChoice)splistHistory.Fields[EF.EFInspectUniquePerm.Column_History_ActionType];
                objSPFieldActionType.Choices.Add(EF.EFInspectUniquePerm.ActionType.Search.ToString());
                objSPFieldActionType.Choices.Add(EF.EFInspectUniquePerm.ActionType.Recover.ToString());
                objSPFieldActionType.DefaultValue = EF.EFInspectUniquePerm.ActionType.Search.ToString();
                objSPFieldActionType.Update();

                splistHistory.Fields[SPBuiltInFieldId.Title].Required = false;
                splistHistory.Fields[SPBuiltInFieldId.Title].Update();
                splistHistory.EnableAttachments = false;
                splistHistory.Update();

                oViewHistory = splistHistory.DefaultView;
                oViewFieldsHistory = oViewHistory.ViewFields;
                oViewFieldsHistory.Add(splistHistory.Fields[SPBuiltInFieldId.Modified].InternalName);
                oViewFieldsHistory.Delete(splistHistory.Fields[SPBuiltInFieldId.LinkTitle].InternalName);
                oViewFieldsHistory.Add(splistHistory.Fields[SPBuiltInFieldId.Title].InternalName);
                oViewFieldsHistory.Add(splistHistory.Fields[EF.EFInspectUniquePerm.Column_History_WebCount]);
                oViewFieldsHistory.Add(splistHistory.Fields[EF.EFInspectUniquePerm.Column_History_ListCount]);
                oViewFieldsHistory.Add(splistHistory.Fields[EF.EFInspectUniquePerm.Column_History_LibraryCount]);
                oViewFieldsHistory.Add(splistHistory.Fields[EF.EFInspectUniquePerm.Column_History_FolderCount]);
                oViewFieldsHistory.Add(splistHistory.Fields[EF.EFInspectUniquePerm.Column_History_ItemCount]);
                oViewFieldsHistory.Add(splistHistory.Fields[EF.EFInspectUniquePerm.Column_History_FileCount]);
                oViewFieldsHistory.Add(splistHistory.Fields[EF.EFInspectUniquePerm.Column_History_ActionType]);
                oViewHistory.Query = @"<OrderBy><FieldRef Name='ID' Ascending='FALSE' /></OrderBy>";
                //oViewHistory.TabularView = false;
                oViewHistory.RowLimit = 5;
                oViewHistory.Update();
            }
            catch (Exception ex)
            {
                logDebug(string.Format(@"EFInspectUniquePerm, initLists(), ex.Message={0}", ex.Message));
                logDebug(string.Format(@"EFInspectUniquePerm, initLists(), ex.StackTrace={0}", ex.StackTrace));

                throw;
            }
        }

        public void initAdminPage(SPSite site)
        {
            SPDocumentLibrary spDocPageLib = null;

            SPWeb objSPWeb = site.RootWeb;
            Guid guidSitePages = Guid.Empty;
            SPList objSPList = objSPWeb.Lists.TryGetList(EF.EFInspectUniquePerm.DocLib_SitePages_Title);
            if (objSPList == null)
            {
                guidSitePages = objSPWeb.Lists.Add(EF.EFInspectUniquePerm.DocLib_SitePages_PathName, "", SPListTemplateType.DocumentLibrary);
                objSPList = objSPWeb.Lists[guidSitePages];
                objSPList.Title = EF.EFInspectUniquePerm.DocLib_SitePages_Title;
                objSPList.Update();
            }
            else
            {
                guidSitePages = objSPList.ID;
                foreach (SPListItem item in objSPList.Items)
                {
                    if (item.File.Name.StartsWith(EF.EFInspectUniquePerm.AdminPage_Name, StringComparison.InvariantCultureIgnoreCase))
                    {
                        item.Delete();
                        break;
                    }
                }
            }
            spDocPageLib = (SPDocumentLibrary)objSPWeb.Lists[guidSitePages];

            string strPageUrl = AddWebPartPage(EF.EFInspectUniquePerm.AdminPage_Name, EF.EFInspectUniquePerm.AdminPage_Title, objSPWeb, spDocPageLib, 2, "WebPartPage", "");

            //string strListUrl = string.Empty;
            ListViewWebPart objListViewWebPart = null;

            try
            {
                objSPList = objSPWeb.Lists.TryGetList(EF.EFInspectUniquePerm.History_ListTitle);
                if (objSPList == null)
                    throw new ArgumentException("History List(" + EF.EFInspectUniquePerm.History_ListTitle + ") not found.");
                objListViewWebPart = AddListViewToPage(objSPWeb, strPageUrl, objSPList.DefaultView, EF.EFInspectUniquePerm.Zone_RightColumn, 1, @"Running history");

                //web part
                //objListViewWebPart = AddWebPartToPage(objSPWeb, strPageUrl, objSPList.DefaultView, EFInspectUniquePerm.Zone_RightColumn, 1, @"Action");

                objSPList = objSPWeb.Lists.TryGetList(EF.EFInspectUniquePerm.Result_ListTitle);
                if (objSPList == null)
                    throw new ArgumentException("Result List(" + EF.EFInspectUniquePerm.Result_ListTitle + ") not found.");
                objListViewWebPart = AddListViewToPage(objSPWeb, strPageUrl, objSPList.DefaultView, EF.EFInspectUniquePerm.Zone_Footer, 1, @"Result list");
                EF.EFInspectUniquePerm.SetToolbarTypeFreeForm(objSPWeb, strPageUrl, objListViewWebPart.StorageKey);
                
                EF.vwpInspectuniquePerm.vwpInspectuniquePerm wp = new EF.vwpInspectuniquePerm.vwpInspectuniquePerm();      // your custom webpart instance
                AddWebPartToPage(objSPWeb, strPageUrl, wp, EF.EFInspectUniquePerm.Zone_LeftColumn, 1, @"Action");
            }
            catch (Exception ex)
            {
                logDebug(string.Format(@"ex.Message={0}", ex.Message));
                logDebug(string.Format(@"ex.StackTrace={0}", ex.StackTrace));

                throw;
            }
        }

        // http://jasear.wordpress.com/2009/04/05/webpartpages-programmatically-adding-a-new-web-part-page/
        // http://msdn.microsoft.com/en-us/library/ms450826.aspx
        //WebPartPage templates you can specify:

        //1, Full Page, Vertical
        //2, Header, Footer, 3 Columns
        //3, Header, Left Column, Body
        //4, Header, Right Column, Body
        //5, Header, Footer, 2 Columns, 4 Rows
        //6, Header, Footer, 4 Columns, Top Row
        //7, Left Column, Header, Footer, Top Row, 3 Columns
        //8, Right Column, Header, Footer, Top Row, 3 Columns

        //Type could have the following possible values:

        //WebPartPage
        //BasicPage
        public string AddWebPartPage(string strFileName, string strFileTitle, SPWeb objSPWeb, SPList objSPList, int iWebPartPageTemplate, string strPageType, string strFolderPath)
        {
            SPFile objSPFile = null;
            string postInformation =
            @"<?xml version=""1.0"" encoding=""UTF-8""?>" +
            @"<Method>" +
            @"<SetList Scope=""Request"">" + objSPList.ID + @"</SetList>" +
            @"<SetVar Name=""ID"">New</SetVar>" +
            @"<SetVar Name=""Cmd"">NewWebPage</SetVar>" +
            @"<SetVar Name=""Type"">" + strPageType + @"</SetVar>" +
            @"<SetVar Name=""WebPartPageTemplate"">" + iWebPartPageTemplate + @"</SetVar>" +
            @"<SetVar Name=""Title"">" + strFileName + @"</SetVar>" +
            @"<SetVar Name=""Overwrite"">true</SetVar>" +
            @"</Method>";
            string processBatch = objSPWeb.ProcessBatchData(postInformation);
            if (processBatch.Equals("<Result ID=\"\" Code=\"0\">\r\n</Result>\n", StringComparison.InvariantCultureIgnoreCase))
            {
                string strFileUrl = objSPList.RootFolder.Url + "/" + strFileName;
                if (strFileUrl.EndsWith(".aspx") == false)
                {
                    strFileUrl += ".aspx";
                }
                objSPFile = objSPWeb.GetFile(strFileUrl);
                //if page was in subfolder then move it there
                if (!String.IsNullOrEmpty(strFolderPath))
                {
                    objSPFile.MoveTo(strFileTitle, true);
                }
                SPFolder rootFolder = objSPFile.ParentFolder;

                using (SPLimitedWebPartManager spLimitedWebPartManager = objSPWeb.GetLimitedWebPartManager(strFileUrl, PersonalizationScope.Shared))
                {

                    foreach (System.Web.UI.WebControls.WebParts.WebPart objWebpart in spLimitedWebPartManager.WebParts)
                    {
                        if (objWebpart.ToString() == "Microsoft.SharePoint.WebPartPages.TitleBarWebPart")
                        {
                            TitleBarWebPart objTitleBarWebPart = (TitleBarWebPart)objWebpart;
                            objTitleBarWebPart.HeaderTitle = strFileTitle;
                            spLimitedWebPartManager.SaveChanges(objTitleBarWebPart);
                            break;
                        }
                    }
                    //System.Web.UI.WebControls.WebParts.WebPart objWebPart = spLimitedWebPartManager.WebParts["TitleBar"];
                    //objWebPart.Title = strFileTitle;
                    objSPWeb.Update();
                }

                return objSPFile.Url;
            }

            return string.Empty;
        }

        public static void AddWebPartToPage(
            SPWeb objSPWeb,
            string pageUrl,
            System.Web.UI.WebControls.WebParts.WebPart objWebPart,
            string zoneID,
            int zoneIndex,
            string strWebPartTitle)
        {
            using (SPLimitedWebPartManager spLimitedWebPartManager = objSPWeb.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared))
            {
                objWebPart.Title = strWebPartTitle;
                spLimitedWebPartManager.AddWebPart(objWebPart, zoneID, zoneIndex);
                spLimitedWebPartManager.SaveChanges(objWebPart);
            }

            return;
        }

        public static ListViewWebPart AddListViewToPage(
            SPWeb objSPWeb,
            string pageUrl,
            SPView objSPView,
            string zoneID,
            int zoneIndex,
            string strWebPartTitle)
        {
            ListViewWebPart objListViewWebPart = null;
            string strListUrl = string.Empty;
            string strListViewWebPartID = string.Empty;
            if (string.IsNullOrEmpty(strWebPartTitle))
                strWebPartTitle = objSPView.ParentList.Title;

            using (SPLimitedWebPartManager spLimitedWebPartManager = objSPWeb.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared))
            {
                using (objListViewWebPart = new ListViewWebPart())
                {
                    objListViewWebPart.ListName = objSPView.ParentList.ID.ToString("B").ToUpperInvariant();
                    objListViewWebPart.TitleUrl = objSPView.ServerRelativeUrl;
                    objListViewWebPart.WebId = objSPWeb.ID;
                    objListViewWebPart.Title = strWebPartTitle;
                    objListViewWebPart.ViewGuid = objSPView.ID.ToString();
                    //objListViewWebPart.DisplayTitle = "abcdefg";

                    spLimitedWebPartManager.AddWebPart(objListViewWebPart, zoneID, zoneIndex);
                    strListViewWebPartID = objListViewWebPart.ID;
                }

                //return strListViewWebPartID;
                return objListViewWebPart;
            }
        }

        private System.Web.UI.WebControls.WebParts.WebPart CreateWebPart(SPWeb web, string webPartName)
        {
            SPQuery query = new SPQuery();
            query.Query = String.Format(
                "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Eq></Where>",
                webPartName);

            SPList webPartGallery = null;

            if (null == web.ParentWeb)
            {
                // This is the root web.
                webPartGallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);
            }
            else
            {
                // This is a sub-web.
                webPartGallery = web.ParentWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
            }

            SPListItemCollection webParts = webPartGallery.GetItems(query);

            string typeName = webParts[0].GetFormattedValue("WebPartTypeName");
            string assemblyName = webParts[0].GetFormattedValue("WebPartAssembly");
            ObjectHandle webPartHandle = Activator.CreateInstance(assemblyName, typeName);

            System.Web.UI.WebControls.WebParts.WebPart webPart =
                (System.Web.UI.WebControls.WebParts.WebPart)webPartHandle.Unwrap();
            return webPart;
        }

        public object ConvertValue(string propertyValue, PropertyInfo property)
        {
            if (propertyValue != string.Empty)
            {
                object value = Convert.ChangeType(propertyValue, property.PropertyType);
                return value;
            }

            return null;
        }

        public void SetWebPartProperty(
            SPWeb web,
            string pageUrl,
            string webPartID,
            string propertyName,
            string propertyValue)
        {
            using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared))
            {
                System.Web.UI.WebControls.WebParts.WebPart part = manager.WebParts[webPartID];
                Type runtimeType = part.GetType();
                PropertyInfo property = runtimeType.GetProperty(propertyName);
                object value = ConvertValue(propertyValue, property);
                property.SetValue(part, value, null);
                manager.SaveChanges(part);
            }
        }

        public void AddWebPartConnection(
            SPWeb web,
            string pageUrl,
            string providerWebPartID,
            string consumerWebPartID,
            string providerConnectionPointName,
            string consumerConnectionPointName)
        {
            using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared))
            {
                System.Web.UI.WebControls.WebParts.WebPart provider = manager.WebParts[providerWebPartID];
                System.Web.UI.WebControls.WebParts.WebPart consumer = manager.WebParts[consumerWebPartID];

                ProviderConnectionPointCollection providerPoints = manager.GetProviderConnectionPoints(provider);
                ConsumerConnectionPointCollection consumerPoints = manager.GetConsumerConnectionPoints(consumer);

                ProviderConnectionPoint providerPoint = null;

                foreach (ProviderConnectionPoint point in providerPoints)
                {
                    if (String.Equals(providerConnectionPointName, point.DisplayName, StringComparison.OrdinalIgnoreCase))
                    {
                        providerPoint = point;
                        break;
                    }
                }

                ConsumerConnectionPoint consumerPoint = null;

                foreach (ConsumerConnectionPoint point in consumerPoints)
                {
                    if (String.Equals(consumerConnectionPointName, point.DisplayName, StringComparison.OrdinalIgnoreCase))
                    {
                        consumerPoint = point;
                        break;
                    }
                }

                manager.SPConnectWebParts(provider, providerPoint, consumer, consumerPoint);
            }
        }

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite objSPSite = new SPSite(site.ID))
                {
                    using (SPWeb objSPWeb = objSPSite.RootWeb)
                    {
                        try
                        {
                            initLists(objSPSite);
                            initAdminPage(objSPSite);
                        }
                        catch (Exception ex)
                        {
                            logDebug(string.Format(@"EFInspectUniquePerm, FeatureActivated(), ex.Message={0}", ex.Message));
                            logDebug(string.Format(@"EFInspectUniquePerm, FeatureActivated(), ex.StackTrace={0}", ex.StackTrace));
                            throw;
                        }
                    }
                }

                //SPWebService contentService = SPWebService.ContentService;
                //contentService.WebConfigModifications.Add(GetConfigModification());
                //contentService.Update();
                //contentService.ApplyWebConfigModifications();
            });
        }

        //public SPWebConfigModification GetConfigModification()
        //{
        //    string assemblyValue = typeof(EF.EFInspectUniquePerm).Assembly.FullName;
        //    string namespaceValue = typeof(EF.EFInspectUniquePerm).Namespace;
        //    SPWebConfigModification modification = new SPWebConfigModification(
        //        string.Format(CultureInfo.CurrentCulture,
        //            @"authorizedType[@Assembly='{0}'][@Namespace='{1}'][@TypeName='*'][@Authorized='True']",
        //            assemblyValue, namespaceValue),
        //        @"configuration/System.Workflow.ComponentModel.WorkflowCompiler/authorizedTypes");
        //    modification.Owner = "EFSPWFActivities";
        //    modification.Sequence = 0;
        //    modification.Type = SPWebConfigModification.
        //    SPWebConfigModificationType.EnsureChildNode;
        //    modification.Value = Environment.NewLine + string.Format(CultureInfo.CurrentCulture,
        //        @" <authorizedType Assembly=""{0}"" Namespace=""{1}"" TypeName=""*"" Authorized=""True"" /> ",
        //        assemblyValue, namespaceValue);
        //    //Trace.TraceInformation(@"getUserLoginsByGroupNameEventReceiver SPWebConfigModification value: {0}", modification.Value);
        //    return modification;
        //}

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            SPList splistHistory = null;
            SPList splistResult = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite objSPSite = new SPSite(site.ID))
                {
                    using (SPWeb objSPWeb = objSPSite.RootWeb)
                    {
                        //delete jobs
                        string strWebTitle = objSPWeb.Title;

                        //delete lists
                        splistHistory = objSPWeb.Lists.TryGetList(EF.EFInspectUniquePerm.History_ListTitle);
                        if (splistHistory != null)
                            splistHistory.Delete();

                        splistResult = objSPSite.RootWeb.Lists.TryGetList(EF.EFInspectUniquePerm.Result_ListTitle);
                        if (splistResult != null)
                            splistResult.Delete();

                        //delete admin page
                        Guid guidSitePages = Guid.Empty;
                        SPList objSPList = objSPWeb.Lists.TryGetList(EF.EFInspectUniquePerm.DocLib_SitePages_Title);
                        if (objSPList != null)
                        {
                            guidSitePages = objSPList.ID;
                            foreach (SPListItem item in objSPList.Items)
                            {
                                if (item.File.Name.StartsWith(EF.EFInspectUniquePerm.AdminPage_Name, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    item.Delete();
                                    break;
                                }
                            }
                        }

                        //logDebugHistory(@"Feature deactivated. Job (" + strJobName + ") deleted.");
                    }
                }
            });
        }

        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
